package user

import (
	"github.com/labstack/echo"
	"github.com/labstack/echo-contrib/session"
	"maki/model"
	"maki/utils"
	"net/http"
)

// Login 登入
func Login(ctx echo.Context) error {
	data := struct {
		Username string `validate:"required"`
		Password string `validate:"required"`
	}{}
	err := utils.BindAndValidate(ctx, &data)
	if err != nil {
		return err
	}
	var user model.User
	if status := model.DB.First(&user, "username = ?", data.Username); status.Error != nil {
		return utils.ErrLoginFailed
	}
	if !user.CheckPassword(data.Password) {
		return utils.ErrLoginFailed
	}
	v, _ := session.Get("user", ctx)
	v.Values["ID"] = user.ID
	v.Save(ctx.Request(), ctx.Response())
	return ctx.JSON(http.StatusOK, utils.NewResult(user))
}

func GetProfile(ctx echo.Context) error {
	u := ctx.Get("user")
	if user, ok := u.(*model.User); !ok {
		return utils.ErrUserNotLogin
	} else {
		return ctx.JSON(http.StatusOK, utils.NewResult(user))
	}
}

// Logout 登出
func Logout(ctx echo.Context) error {
	v, _ := session.Get("user", ctx)
	for k := range v.Values {
		delete(v.Values, k)
	}
	v.Save(ctx.Request(), ctx.Response())
	return ctx.JSON(http.StatusOK, utils.NewResult("success"))
}

// remove me
func CreateUser(ctx echo.Context) error {
	user := model.User{
		Username: "admin",
	}
	user.SetPassword("adminadmin")
	if status := model.DB.Create(&user); status.Error != nil {
		return status.Error
	}
	return ctx.JSON(http.StatusOK, utils.NewResult("success"))
}
